package UDP;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer
{
    public static void main (String[] args)
    {
        //创建服务端接收数据对象的DatagramSocket对象
        try(DatagramSocket datagramSocket = new DatagramSocket(9999))
        {
            //创建数据缓冲区
            byte[] bytes = new byte[1024];
            //创数据报包对象
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            //等待客户端发送的数据
            datagramSocket.receive(datagramPacket);
            
//            //取出数据
//            String str = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
//            System.out.println(str);

//            //基本数据类型
//            //这个数据转换的知识很重要
//            try(DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(datagramPacket.getData())))
//            {
//                System.out.println(dataInputStream.readInt());
//            }
        
            //自定义对象类型
            try(ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(datagramPacket.getData())))
            {
                System.out.println(objectInputStream.readObject());
            }
        }
        catch(IOException | ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}
